package com.parsechina.hpush.broker.internal.unique;

import com.google.common.collect.Maps;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public final class Yeast {
    private static char[] alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".toCharArray();
    private static int length;
    private static int seed;
    private static String prev;
    private static Map<Character, Integer> map;

    private Yeast() {
    }

    public static String encode(long num) {
        StringBuilder encoded = new StringBuilder();
        long dividedNum = num;

        do {
            encoded.insert(0, alphabet[(int)(dividedNum % (long)length)]);
            dividedNum /= (long)length;
        } while(dividedNum > 0L);

        return encoded.toString();
    }

    public static long decode(String str) {
        long decoded = 0L;
        char[] var3 = str.toCharArray();
        int var4 = var3.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            char c = var3[var5];
            decoded = decoded * (long)length + (long)(Integer)map.get(c);
        }

        return decoded;
    }

    public static String yeast() {
        String now = encode((new Date()).getTime());
        if (!now.equals(prev)) {
            seed = 0;
            prev = now;
            return now;
        } else {
            return now + "." + encode((long)(seed++));
        }
    }

    static {
        length = alphabet.length;
        seed = 0;
        map = Maps.newHashMapWithExpectedSize(length);

        for(int i = 0; i < length; ++i) {
            map.put(alphabet[i], i);
        }

    }
}
